package com.ilxqx.framework.schedule.job;

import com.ilxqx.framework.system.upload.enumeration.FileTypeEnum;
import com.ilxqx.framework.system.upload.qiniu.service.QiNiuBucketManagerService;
import com.ilxqx.framework.system.upload.qiniu.service.QiNiuImgUploadService;
import com.ilxqx.framework.util.SpringUtils;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

/**
 * 删除无用文件Job
 * @author venus
 */
@Slf4j
@Setter
public class FileDeletionJob implements Job {

    /**
     * 文件唯一标识key
     */
    private String key;

    /**
     * 七牛空间管理服务类
     */
    private String fileType;


    /**
     * <p>
     * Called by the <code>{@link Scheduler}</code> when a <code>{@link Trigger}</code>
     * fires that is associated with the <code>Job</code>.
     * </p>
     *
     * <p>
     * The implementation may wish to set a
     * {@link JobExecutionContext#setResult(Object) result} object on the
     * {@link JobExecutionContext} before this method exits.  The result itself
     * is meaningless to Quartz, but may be informative to
     * <code>{@link JobListener}s</code> or
     * <code>{@link TriggerListener}s</code> that are watching the job's
     * execution.
     * </p>
     *
     * @param context job执行上下文
     * @throws JobExecutionException if there is an exception while executing the job.
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("有上传的文件长时间未被使用，开始执行清除任务");
        // 获取文件管理服务类
        QiNiuBucketManagerService managerService;
        switch (this.getType()) {
            case IMAGE:
                managerService = SpringUtils.getBean(QiNiuImgUploadService.class);
                break;
            case FILE:
                managerService = SpringUtils.getBean(QiNiuImgUploadService.class);
                break;
            default:
                managerService = null;
        }
        // 如果managerService为空，则任务执行失败
        if (managerService == null) {
            log.warn("任务执行失败，原因[获取不到对应的BucketManagerService]");
            return;
        }
        if (managerService.delete(this.key)) {
            log.info("任务执行成功，文件清除成功");
        } else {
            log.warn("任务执行失败，具体查看日志中的报错信息");
        }
    }

    /**
     * 获取文件类型枚举类型
     * @return 枚举类型
     */
    private FileTypeEnum getType() {
        return FileTypeEnum.valueOf(this.fileType);
    }

}
